<script setup lang="ts">
import { reactive, ref, shallowRef } from 'vue';
import type { FormInstance } from 'vant';
import { showSuccessToast } from 'vant';
import { useLargenScreen } from '@/composables/useLargenScreen';
import { shopproductSH } from '@/common/api/productAudit';

// 监听浏览器窗口变化
useLargenScreen();

const emit = defineEmits<{
  (e: 'onRefresh'): void;
}>();

// 定义引用
const formRef = shallowRef<FormInstance>();

const show = ref(false);
const form = reactive({
  pid: '', // 商品ID
  status: '', // 审核状态 1通过，3失败
  reason: '', // 拒绝原因
});
const emptyForm = JSON.stringify(form);

const onSubmit = async () => {
  try {
    await formRef.value?.validate();
    await shopproductSH({ ...form });
    show.value = false;
    emit('onRefresh');
    // showSuccessToast('操作成功');
    return Promise.resolve();
  } catch {
    return Promise.reject();
  }
};

const beforeClose = (action: string) => {
  if (action === 'cancel') {
    return true;
  } else {
    return new Promise<boolean>((resolve) => {
      onSubmit()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    });
  }
};

const onClosed = () => {
  Object.assign(form, JSON.parse(emptyForm));
  formRef.value?.resetValidation();
};

defineExpose({
  open(id: string, status: '1' | '3') {
    form.pid = id;
    form.status = status;
    show.value = true;
  },
});
</script>
<template>
  <div class="auditDialog">
    <van-dialog v-model:show="show" title="审核" show-cancel-button :before-close="beforeClose" @closed="onClosed">
      <van-form class="py-3" label-width="70px" ref="formRef">
        <van-cell-group inset>
          <van-field
            :model-value="form.status === '1' ? '审核通过' : '审核拒绝'"
            name="oid"
            label="审核状态"
            readonly
          />
          <van-field
            v-if="form.status === '3'"
            v-model="form.reason"
            rows="2"
            autosize
            label="拒绝原因"
            type="textarea"
            maxlength="50"
            placeholder="请输入拒绝原因"
            :rules="[{ required: true, message: '请填写拒绝原因' }]"
            show-word-limit
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
  </div>
</template>
<style lang="less" scoped>
.auditDialog {
}
</style>
